import axios from "axios";
import fs from "fs";
import path from "path";
import AdmZip from "adm-zip";
import { promisify } from "util";
import { fileURLToPath } from "url";
import czdbService from "../src/services/czdb.service.js";
import dotenv from "dotenv";

// 加载环境变量
dotenv.config();

const writeFile = promisify(fs.writeFile);
const mkdir = promisify(fs.mkdir);

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const CZDB_URL =
  process.env.CZDB_DOWNLOAD_URL ||
  "https://www.cz88.net/api/communityIpAuthorization/communityIpDbFile";
const CZDB_DIR = path.join(path.dirname(__dirname), "czdb");

async function initializeDatabase() {
  console.log("=== CZDB 数据库更新脚本 ===");
  console.log("时间:", new Date().toISOString());
  console.log("配置信息:");
  console.log("- 数据库目录:", CZDB_DIR);
  console.log("- 下载地址:", CZDB_URL);
  console.log("- IPv4数据库:", process.env.CZDB_IPV4_PATH);
  console.log("- IPv6数据库:", process.env.CZDB_IPV6_PATH);
  console.log("\n=== 初始化数据库 ===");
  const ipv4DbPath = process.env.CZDB_IPV4_PATH;
  const ipv6DbPath = process.env.CZDB_IPV6_PATH;
  const key = process.env.CZDB_KEY;

  if (!key) {
    throw new Error("错误: 缺少CZDB_KEY环境变量");
  }

  if (!ipv4DbPath && !ipv6DbPath) {
    throw new Error("错误: 至少需要提供一个数据库文件路径");
  }

  try {
    const initialized = czdbService.initialize(ipv4DbPath, ipv6DbPath, key);
    if (initialized) {
      console.log("✓ 数据库初始化成功");
      return true;
    } else {
      throw new Error("数据库初始化失败");
    }
  } catch (error) {
    console.error("✗ 数据库初始化失败:", error.message);
    throw error;
  }
}

async function downloadAndUpdateCZDB() {
  try {
    console.log("\n=== 检查目录 ===");
    // 检查目录是否存在
    if (fs.existsSync(CZDB_DIR)) {
      console.log("✓ 数据库目录已存在");
    } else {
      console.log("- 创建数据库目录...");
      await mkdir(CZDB_DIR, { recursive: true });
      console.log("✓ 数据库目录创建成功");
    }

    // 下载文件
    console.log("\n=== 下载数据库 ===");
    console.log("- 开始下载...");
    const downloadKey = process.env.CZDB_DOWNLOAD_KEY;
    if (!downloadKey) {
      throw new Error("错误: 缺少CZDB_DOWNLOAD_KEY环境变量");
    }

    const response = await axios({
      method: "get",
      url: CZDB_URL,
      params: {
        fn: "czdb",
        key: downloadKey,
      },
      responseType: "arraybuffer",
      timeout: 60000, // 60秒超时
    });

    const fileSize = (response.data.length / 1024 / 1024).toFixed(2);
    console.log(`✓ 下载完成 (${fileSize}MB)`);

    // 保存zip文件
    console.log("\n=== 解压数据库 ===");
    const tempZipPath = path.join(CZDB_DIR, "temp.zip");
    console.log("- 保存临时文件...");
    await writeFile(tempZipPath, response.data);
    console.log("✓ 临时文件保存成功:", tempZipPath);

    // 解压文件
    console.log("- 开始解压...");
    const zip = new AdmZip(tempZipPath);
    zip.extractAllTo(CZDB_DIR, true);
    console.log("✓ 解压完成");

    // 删除临时zip文件
    console.log("- 清理临时文件...");
    fs.unlinkSync(tempZipPath);
    console.log("✓ 临时文件清理完成");

    // 显示更新后的文件列表
    const files = fs.readdirSync(CZDB_DIR);
    console.log("\n=== 数据库文件 ===");
    files.forEach((file) => console.log(`- ${file}`));

    // 重新初始化数据库
    console.log("\n=== 重新初始化数据库 ===");
    await initializeDatabase();

    console.log("\n✓ 数据库更新完成!");
    return true;
  } catch (error) {
    console.error("\n✗ 数据库更新失败!");
    console.error("错误详情:");
    console.error(`- 类型: ${error.name}`);
    console.error(`- 信息: ${error.message}`);
    if (error.response) {
      console.error(`- 状态码: ${error.response.status}`);
      console.error(`- 响应数据: ${JSON.stringify(error.response.data)}`);
    }
    if (process.env.NODE_ENV === "development") {
      console.error("- 堆栈:", error.stack);
    }
    throw error;
  }
}

process.on("unhandledRejection", (reason, promise) => {
  console.error("\n✗ 未捕获的Promise拒绝:");
  console.error("- 原因:", reason);
});

// ES Module 中判断是否为直接运行
if (import.meta.url === `file://${process.argv[1]}`) {
  (async () => {
    try {
      await downloadAndUpdateCZDB();
    } catch (error) {
      process.exit(1);
    }
  })();
}

export default downloadAndUpdateCZDB;
